package com.wjk.easy.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.wjk.easy.R;
import com.wjk.easy.db.Exam;

import java.util.List;

public class ExamListAdapter extends RecyclerView.Adapter {
    private Context context;
    private List<Exam> list;
    private int mSelectedPos=0;

    public ExamListAdapter(Context context, List<Exam> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_exam_menu, parent,
                false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final Exam exam = list.get(position);
        MyViewHolder h = (MyViewHolder) holder;
        h.tv_exam_name.setText(exam.getName());
        h.tv_exam_name.setSelected(position==mSelectedPos);
        h.tv_exam_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(changeListener!=null){
                    changeListener.onExamChange(exam);
                }
                if(position!=mSelectedPos){
                    mSelectedPos = position;
                    notifyDataSetChanged();
                }
            }
        });
    }

    public void setExamChangeListener(OnExamChangeListener changeListener){
        this.changeListener = changeListener;
    }

    public void switchItem(int examId){
        Exam item = getItem(examId);
        if(item !=null){
            mSelectedPos = list.indexOf(item);
            notifyDataSetChanged();
        }
    }

    public Exam getItem(int examId){
        for (int i=0;i<list.size();i++) {
            if(list.get(i).getId()==examId){
                return list.get(i);
            }
        }
        return null;
    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    /**
     * ViewHolder的类，用于缓存控件
     */
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv_exam_name;
        RelativeLayout ll_exam_container;

        MyViewHolder(View view) {
            super(view);
            tv_exam_name = view.findViewById(R.id.tv_exam_name);
            ll_exam_container = view.findViewById(R.id.ll_exam_container);
        }
    }
    private OnExamChangeListener changeListener;
    public interface OnExamChangeListener{
        void onExamChange(Exam e);
    }
}
